package com.tedu.openmedical.medicalsystem.base.shiroConfig;


import com.auth0.jwt.interfaces.DecodedJWT;
import com.tedu.openmedical.medicalsystem.base.utils.JWTToken;
import com.tedu.openmedical.medicalsystem.base.utils.JwtUtils;
import com.tedu.openmedical.medicalsystem.user.pojo.entity.User;
import com.tedu.openmedical.medicalsystem.user.pojo.vo.ActiveUser;
import com.tedu.openmedical.medicalsystem.user.service.UserService;
import lombok.SneakyThrows;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.codec.Hex;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;



/**
 * 自定义Realm，Shiro 中的一个概念，代表一个安全数据源，负责与数据源交互以获取认证和授权信息。
 */
public class UserRealm  extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 登录认证
     * @param authenticationToken 登录token
     * @return AuthenticationInfo
     * @throws AuthenticationException 认证失败异常
     */
    @SneakyThrows
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        JWTToken jwtToken = (JWTToken) authenticationToken;
        String token = (String) jwtToken.getPrincipal();
        DecodedJWT verify = JwtUtils.verify(token);
        String userName = verify.getClaim("name").asString();
        return new SimpleAuthenticationInfo(userName, token, getName());
    }

    /**
     * 授权 登录后判断用户是否拥有某个权限
     * @param principals PrincipalCollection：这是一个接口，用于封装用户的身份信息。
     * @return AuthorizationInfo
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        ActiveUser activeUser = (ActiveUser) principals.getPrimaryPrincipal();
        return new SimpleAuthorizationInfo();
    }
}
